package com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.aggregate;

import org.apache.commons.lang3.StringUtils;

import com.pingan.haofang.searchcloud.api.query.parser.dbobject.FunctionConfig;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.SqlNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.sqlnode.ColumnNode;
import com.pingan.haofang.searchcloud.api.query.parser.dbobject.util.SqlNodeUtil;

/**
 * DISTINCT
 * 
 * @author LUYI374
 * @date 2017年7月11日
 * @since 1.0.0
 */
public class Distinct extends AggregateFunction {

    private static final int VALUE_PARAM_COUNT = 2;

    private boolean allDistinct;

    public Distinct() {
        setName(FunctionConfig.DISTINCT.name);
    }

    @Override
    public Object getValue(Object...params) {
        assertParamCount(params, VALUE_PARAM_COUNT);
        assertParamType(params, Number.class);
        return Long.parseLong(params[0].toString()) + Long.parseLong(params[1].toString());
    }

    @Override
    public int getParamCount() {
        return 1;
    }

    public boolean isAllDistinct() {
        return allDistinct;
    }

    public void setAllDistinct(boolean allDistinct) {
        this.allDistinct = allDistinct;
    }

    public String getFullName() {
        StringBuilder sb = new StringBuilder();
        if (allDistinct) {
            if (params != null) {
                for (SqlNode param : params) {
                    if (SqlNodeUtil.isColumn(param)) {
                        ColumnNode columnNode = (ColumnNode) param;
                        if (StringUtils.isNotBlank(columnNode.getSchema())) {
                            sb.append(columnNode.getSchema()).append(".");
                        }
                        sb.append(columnNode.getColumnName());
                    } else {
                        sb.append(param.toString());
                    }
                }
            }
        } else {
            sb.append(name).append("(");
            if (params != null) {
                for (SqlNode param : params) {
                    if (SqlNodeUtil.isColumn(param)) {
                        ColumnNode columnNode = (ColumnNode) param;
                        if (StringUtils.isNotBlank(columnNode.getSchema())) {
                            sb.append(columnNode.getSchema()).append(".");
                        }
                        sb.append(columnNode.getColumnName());
                    } else {
                        sb.append(param.toString());
                    }
                }
            }
            sb.append(")");
        }
        return sb.toString();
    }
}
